#include <stdlib.h>
#include "GARand.h"

// #include <stdio.h>

#ifndef GD
#include <time.h>
#endif

static unsigned int soft_rand_seed = 0;

void TRNGInit(void);
unsigned int get_rand_data(void);

/** 随机数产生初始化
 *
 *
 */
void GARandInit()
{
#ifndef GD
    srand((unsigned)time(NULL)); // 使用系统时间
#else 
    TRNGInit();
#endif
}

/** 产生随机数
 *   输入 随机数范围 [0,range)
 *   返回 随机数
 */
unsigned int GARand(int range)
{
    unsigned int rd = 0;
#ifdef USE_TRNG
    rd = trng_get_true_random_data() % range;
#else
    rd = (unsigned int)rand() % range;
    // printf("rand: %d\r\n", rd);
#endif
    return rd;
}

void TRNGInit(void)
{
#ifdef USE_TRNG
    rcu_periph_clock_enable(RCU_TRNG);
    trng_deinit();
    trng_enable();

    while (trng_flag_get(TRNG_FLAG_DRDY) == RESET)
        ;
    get_rand_data();
#else
    srand(soft_rand_seed);
#endif
}

unsigned int get_soft_rand_data(void)
{
#ifdef GD
    return __RBIT(rand());
#endif
    return 0;
}

void soft_rand_seed_plus(void)
{
    // 需要定时器触发
    soft_rand_seed++;
}

unsigned int get_rand_data(void)
{
#ifdef USE_TRNG
    while (trng_flag_get(TRNG_FLAG_DRDY) == RESET)
        ;
    return trng_get_true_random_data();
#else
    return get_soft_rand_data();
#endif
}
